package com.wbao.dianniu.ui;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.arlen.photo.photopickup.presenter.PhotoPresenter;
import com.arlen.photo.photopickup.util.MediaUtils;
import com.arlen.photo.photopickup.view.ImageLookActivity;
import com.arlen.photo.photopickup.view.PhotoPickupActivity;
import com.arlen.photo.photopickup.widget.SimpleGrid;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IAskListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.AskManager;
import com.wbao.dianniu.manager.QaDataChangeManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * 提问
 * 
 * @author yejianjun
 * 
 */
public class AskActivity extends Activity implements OnClickListener,IAskListener {

	private final int ASK_TYPE = 1;
	private ImageButton cancel;
	private Button submit;
	private Dialog dialog;
	private EditText mEditText;
	private final int IMAGE_OPEN = 1; // 打开图片标记
	private final int TAKE_PHOTO = 2; // 打开图片标记
	private AskManager manager;
	private Dialog pDialog;
	private TextView contentLength;
	private SimpleGrid mSimpleGrid;
	 private PhotoPresenter mPhotoPresenter;
	 private boolean isClick = false;
	 private ImageView picImage;
	 private final int showAliasName = 1;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Utils.setTranslucentStatus(this,true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
		}
		setContentView(R.layout.activity_ask_question);
        mPhotoPresenter = new PhotoPresenter(this,"goods");
		initview();
		manager = new AskManager(this);
		manager.addAskListener(this);
		
	}

	private void initview() {
		((TextView) findViewById(R.id.ask_title)).setText("问答");
		cancel = (ImageButton) findViewById(R.id.ask_back_button);
		submit = (Button) findViewById(R.id.ask_submit);
		
		mEditText = (EditText) findViewById(R.id.ask_editText);
		mEditText.addTextChangedListener(watcher);
		contentLength = (TextView) findViewById(R.id.Content_length);
		cancel.setOnClickListener(this);
		submit.setOnClickListener(new NoDoubleClickListener() {
			
			@Override
			public void onNoDoubleClick(View v) {
				// TODO Auto-generated method stub
				String content;
				content = mEditText.getText().toString().trim();
				if (TextUtils.isEmpty(content)) {
					Notification.showToastMsg(AskActivity.this, "内容不能为空");
					return;
				}
				
				if(!isClick){
					isClick = true;
					pDialog = LoadingWaitDialog.createLoadingDialog(AskActivity.this, "");
					pDialog.show();
					// 把图片列表转化成string
					String questImgs = listToString(mPhotoPresenter.getSelectedList(),',');
					manager.ask(GlobalContext.accountId, ASK_TYPE, content, questImgs, showAliasName);
				}
			}
		});

		mSimpleGrid = (SimpleGrid) findViewById(R.id.img_grid);
		mPhotoPresenter.initView(mSimpleGrid);
		mSimpleGrid.setMaxItemPerRow(4);
		mSimpleGrid.setItemMarginHor(7f);
		mSimpleGrid.setItemMarginVer(7f);
		mPhotoPresenter.updateImgGrid();
		
		 picImage = (ImageView) findViewById(R.id.qa_chose_image);
	     picImage.setOnClickListener(this);
	}

	TextWatcher watcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			contentLength.setText(s.length() + "/150");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ask_back_button:
			finish();
			break;
//		case R.id.ask_submit: // 提交发布
//			String content;
//			content = mEditText.getText().toString().trim();
//			if (TextUtils.isEmpty(content)) {
//				Notification.showToastMsg(this, "内容不能为空");
//				return;
//			}
//			
//			if(!isClick){
//				isClick = true;
//				pDialog = new ProgressDialog(this);
//				pDialog.show();
//				// 把图片列表转化成string
//				String questImgs = listToString(mPhotoPresenter.getSelectedList(),',');
//				manager.ask(GlobalContext.accountId, ASK_TYPE, content, questImgs);
//			}
//			break;
		case R.id.btn_cancel:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			break;
		case R.id.btn_take_photo:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			//拍照
			 Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			 takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"temp.jpg")));
			 startActivityForResult(takeIntent, TAKE_PHOTO);
			break;
		case R.id.btn_pick_photo:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			//选择图片
			Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, IMAGE_OPEN);
			break;
		case R.id.qa_chose_image:
			mPhotoPresenter.choseImage();
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		 MobclickAgent.onResume(this);
	}

	@Override
	public void onAskFailure(int errorCode, String errorMsg) {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		isClick = false;
	}

	@Override
	public void onAskSuccess(QaResponse addData) {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		isClick = false;
		QaDataChangeManager.getInstance().addOneDataNotify(addData);
		finish();
	}
	
	private String listToString(ArrayList<MediaUtils.ImageProperty> list, char separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				sb.append(list.get(i).desc);
			} else {
				sb.append(list.get(i).desc);
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        if (requestCode == PhotoPickupActivity.REQUEST_CODE) {
	            if (resultCode == RESULT_OK) {
	                if (PhotoPickupActivity.getSelectedImgPros(data) != null) {
	                    mPhotoPresenter.pickPhotoResult(data);
	                }
	            }
	        } else if (requestCode == ImageLookActivity.REQUEST_CODE) {
	            if (resultCode == RESULT_OK) {
	                if (data != null) {
	                    mPhotoPresenter.lookImageResult(data);
	                }
	            }
	        }
	    }
	
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != pDialog && pDialog.isShowing()) {
			pDialog.dismiss();
		}
	}
}
